//
//  ViewController.m
//  LinkMap
//
//  Created by Suteki(67111677@qq.com) on 4/8/16.
//  Copyright © 2016 Apple. All rights reserved.
//

#import "ViewController.h"
#import "ObjectResult.h"
#import "SymbolParser.h"
#import "SymbolResultGenerator.h"
#import "UnusedClassesDetector.h"
#import "SymbolResultFilter.h"
#import "LinkMapParseResult.h"

@interface ViewController()

@property (weak) IBOutlet NSTextField *filePathField;//显示选择的文件路径
@property (weak) IBOutlet NSProgressIndicator *indicator;//指示器
@property (weak) IBOutlet NSTextField *searchField;

@property (weak) IBOutlet NSScrollView *contentView;//分析的内容
@property (unsafe_unretained) IBOutlet NSTextView *contentTextView;
@property (weak) IBOutlet NSButton *groupButton;
@property (weak) IBOutlet NSButton *unusedClassesCheckBtn;
@property (weak) IBOutlet NSButton *startButton;


@property (strong) NSURL *linkMapFileURL;
@property (strong) NSString *linkMapContent;

@property (strong) NSString *result;//分析的结果

@property (nonatomic, strong) SymbolParser *parser;
@property (nonatomic, strong) SymbolResultGenerator *generator;
@property (nonatomic, strong) UnusedClassesDetector *unusedClassesDetector;
@property (nonatomic, strong) SymbolResultFilter *filter;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.indicator.hidden = YES;
    
    _parser = [SymbolParser new];
    _generator = [SymbolResultGenerator new];
    _unusedClassesDetector = [UnusedClassesDetector new];
    _filter = [SymbolResultFilter new];
    
    _contentTextView.editable = NO;
    
    _contentTextView.string = @"使用方式1：\n\
    1.在XCode中开启编译选项Write Link Map File \n\
    XCode -> Project -> Build Settings -> 把Write Link Map File选项设为yes，并指定好linkMap的存储位置 \n\
    2.工程编译完成后，在编译目录里找到Link Map文件（txt类型） \n\
    默认的文件地址：~/Library/Developer/Xcode/DerivedData/XXX-xxxxxxxxxxxxx/Build/Intermediates/XXX.build/Debug-iphoneos/XXX.build/ \n\
    3.回到本应用，点击“选择文件”，打开Link Map文件  \n\
    4.点击“开始”，解析Link Map文件 \n\
    5.点击“输出文件”，得到解析后的Link Map文件 \n\
    6. * 输入目标文件的关键字(例如：libIM)，然后点击“开始”。实现搜索功能 \n\
    7. * 勾选“分组解析”，实现对不同库的目标文件进行分组 \n\
    8. * 勾选“无用代码检测”，会执行不用代码检测流程，需要依赖`blades`工具，工具安装参考[WBBlades是基于`Mach-O`文件解析的工具集，包括无用代码检测（支持`OC`和`Swift`）、包大小分析、无符号表日志符号化。](https://github.com/wuba/WBBlades/blob/master/README_CN.md) \n\
    9. 然后点击“开始”。"
    ;
}

- (IBAction)chooseFile:(id)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    panel.allowsMultipleSelection = NO;
    panel.canChooseDirectories = NO;
    panel.resolvesAliases = NO;
    panel.canChooseFiles = YES;
    
    [panel beginWithCompletionHandler:^(NSInteger result){
        if (result == NSFileHandlingPanelOKButton) {
            NSURL *document = [[panel URLs] objectAtIndex:0];
            _filePathField.stringValue = document.path;
            self.linkMapFileURL = document;
        }
    }];
}

- (IBAction)analyze:(id)sender {
    if (!_linkMapFileURL || ![[NSFileManager defaultManager] fileExistsAtPath:[_linkMapFileURL path] isDirectory:nil]) {
        [self showAlertWithText:@"请选择正确的Link Map文件路径"];
        return;
    }
    
    self.indicator.hidden = NO;
    [self.indicator startAnimation:self];
    [self.startButton setEnabled:NO];
        
    [self.parser startParseWithLinkMapFile:_linkMapFileURL completion:^(BOOL success, NSError *error, LinkMapParseResult *result) {
        
        void (^handleResultBlock)(NSArray *result) = ^(NSArray *result){
            NSString *searchKey = _searchField.stringValue;
            if (_groupButton.state == 1) {
//                _result = [self.generator buildCombinationResultWithSymbols:result searchKey:searchKey];
                _result = [self.generator buildModuleResultWithSymbols:result searchKey:searchKey];
            } else {
                _result = [self.generator buildResultWithSymbols:result searchKey:searchKey];
            }

            self.indicator.hidden = YES;
            [self.indicator stopAnimation:self];
            [self.startButton setEnabled:YES];
            self.contentTextView.string = _result ?: @"";
        };
        
        if (!success) {
            [self showAlertWithText:error.localizedDescription];
        } else {
            if (_unusedClassesCheckBtn.state == 1) {
                NSString *binaryPath = result.binaryPath;// @"/Users/aron/Library/Developer/Xcode/DerivedData/bbframework-fbvqwhusfzvshbeiwfxkzayjttyh/Build/Products/Debug-iphoneos/2d_noSuper_education.app/2d_noSuper_education";
                [_unusedClassesDetector unusedClasses:binaryPath completion:^(NSArray * _Nonnull unusedClasses) {
                    NSArray *filteredResult = [_filter filterWithSymbols:result.objectResults filters:unusedClasses];
                    handleResultBlock(filteredResult);
                }];
            } else {
                handleResultBlock(result.objectResults);
            }
        }
    }];
}

- (IBAction)ouputFile:(id)sender {
    NSOpenPanel* panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setResolvesAliases:NO];
    [panel setCanChooseFiles:NO];
    
    [panel beginWithCompletionHandler:^(NSInteger result) {
        if (result == NSFileHandlingPanelOKButton) {
            NSURL*  theDoc = [[panel URLs] objectAtIndex:0];
            NSMutableString *content =[[NSMutableString alloc]initWithCapacity:0];
            [content appendString:[theDoc path]];
            [content appendString:@"/linkMap.txt"];
            [_result writeToFile:content atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
    }];
}

- (void)showAlertWithText:(NSString *)text {
    NSAlert *alert = [[NSAlert alloc]init];
    alert.messageText = text;
    [alert addButtonWithTitle:@"确定"];
    [alert beginSheetModalForWindow:[NSApplication sharedApplication].windows[0] completionHandler:^(NSModalResponse returnCode) {
    }];
}

@end
